<template>
  <div class="outbox">
    <div class="chart-container">
      <div class="chart-title">就业意向图</div>
      <div ref="employmentIntentionDom" class="outbox-employment-intention"></div>
    </div>
    <div class="chart-container">
      <div class="chart-title">就业状态图</div>
      <div ref="employmentStatusDom" class="outbox-employment-status"></div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted } from 'vue';
import { getEmployData } from '@/api/echarts';
import {getEmploymentStatsAndIntent,getProvinceStats} from '@/api/system/EmploymentInfo.js'
import { Right } from '@element-plus/icons-vue';
const props=defineProps({
  selectedGrade: String
}
)
const employmentIntentionDom = ref(null); // 就业意向图 DOM 容器
const employmentStatusDom = ref(null); // 就业状态图 DOM 容器
const chartsData = ref([]); // 数据存储
const options = ref([]); // 年级选项
const value = ref('');
const employmentIntents = ref([]); // 就业意向数据
const employmentStatus = ref([]); // 就业状态数据
const totalemploymentIntents= ref([]); // 就业意向数据
const totalemploymentStatus= ref([]); // 就业意向数据


let employmentIntentionChart; // 就业意向图实例
let employmentStatusChart; // 就业状态图实例;
// 初始化就业意向图
const initEmploymentIntentionChart = (dom, data) => {
  employmentIntentionChart = echarts.init(dom);
  const option = {
    title: {
      text: '就业意向图',
      left: 'left',
      show: false,
      top: '2%',
      textStyle: {
        fontSize: 25,
        fontWeight: 'bold',
        color: '#00b6ff'
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    
    legend: {
  orient: 'vertical',
  left: 'left',
  data: data.map(item => item.name),
  textStyle: {
    color: '#fff'
  },
  formatter: function (name) {
    const item = data.find(item => item.name === name);
    const total=totalemploymentIntents.value.find(item => item.name ===  props.selectedGrade);
    if (item && totalemploymentIntents.value) {
      const num = (item.value / total.value) * 100;
      return `${name} ${num.toFixed(1)}%`;
    }
    return `${name} 0.00%`;
  }
},
    series: [
      {
        left: '25%',
        name: '就业意向',
        type: 'pie',
        radius: ['30%', '60%'], // 设置内外半径创建环状图
        roseType: 'radius',
        data: data || [],
        avoidLabelOverlap: true, // 避免标签重叠
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
        label: {
          show: true,
          fontSize: 12,
          fontWeight: 'bold',
          position: 'outside',
        },
      },
    ],
  };
  employmentIntentionChart.setOption(option);
};

// 初始化就业状态图
const initEmploymentStatusChart = (dom, data) => {
  employmentStatusChart = echarts.init(dom);
  const option = {
    title: {
      text: '就业状态图',
      left: 'left',
      show: false,
      top: '2%',
      textStyle: {
        fontSize: 25,
        fontWeight: 'bold',
        color: '#00b6ff',
      },
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    legend: {
  orient: 'vertical',
  left: 'left',
  data: data.map(item => item.name),
  textStyle: {
    color: '#fff'
  },
  formatter: function (name) {
    const item = data.find(item => item.name === name);
    const total=totalemploymentStatus.value.find(item => item.name ===  props.selectedGrade);
    if (item && totalemploymentStatus.value) {
      const num = (item.value / total.value) * 100;
      return `${name} ${num.toFixed(1)}%`;
    }
    return `${name} 0.00%`;
  }
},
    series: [
      {
        left: '25%',
        name: '就业状态',
        type: 'pie',
        radius: ['30%', '60%'], // 设置内外半径创建环状图
        roseType: 'radius',
        center: ['50%', '50%'], // 饼图中心点位置
        data: data || [],
        color: ["#0BFC7F", "#A0A0A0", "#F48C02", "#F4023C"],
        avoidLabelOverlap: true, // 避免标签重叠
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          }
        },
        label: {
          show: true,
          fontSize: 10,
          fontWeight: 'bold',
          position: 'outside',
        },
      },
    ],
  };
  employmentStatusChart.setOption(option);
};

// 初始化就业状态图
// const initEmploymentStatusChart = (dom, data) => {
//   employmentStatusChart = echarts.init(dom);
//   const option = {
//     title: {
//       text: '就业状态图',
//       left: 'center',
//       top:'2%',

//       textStyle: {
//         fontSize: 25,
//         fontWeight: 'bold',
//          color:'#00b6ff',
//       },
//     },
//     tooltip: {
//       trigger: 'item',
//       formatter: '{a} <br/>{b} : {c} ({d}%)',
//     },
//     series: [
//       {
//         name: '就业状态',
//         type: 'pie',
//         roseType: 'radius',
//         radius: [10, 80], // 将内外半径调整小
//         data: data || [],
//         color: ["#0BFC7F", "#A0A0A0", "#F48C02", "#F4023C"],
//         emphasis: {
//           itemStyle: {
//             shadowBlur: 10,
//             shadowOffsetX: 0,
//             shadowColor: 'rgba(0, 0, 0, 0.5)',
//           },
//         },
//         label: {
//           show: true,
//           fontSize: 12,
//           fontWeight: 'bold',
//         },
//       },
//     ],
//   };
//   employmentStatusChart.setOption(option);
// };

// 组件挂载后获取数据并初始化图表
onMounted(() => {

  window.addEventListener('resize', resizeCharts); // 添加窗口大小变化监听器
  getEmploymentStatsAndIntent().then((res) => {
    if (res.code === 200) {
      // 提取年级选项
      options.value = res.rows.map((item) => item.name);

      // 就业意向数据
      employmentIntents.value = res.rows.map((item) => ({
        employmentIntent: item.employmentIntents,
        name: item.name,
      }));

      // 就业状态数据
      employmentStatus.value = res.rows.map((item) => ({
        employmentStatu: item.employmentStatuses,
        name: item.name,
      }));
      

res.rows.forEach(element => {
    // console.log(element);
    let taptotal=0;
    element.employmentIntents.forEach(item => {
      taptotal+=item.value;
    })
    let taptotal2=0;
    element.employmentStatuses.forEach(item => {
      taptotal2+=item.value;
    })
    totalemploymentIntents.value.push({
      name:element.name,
      value:taptotal
    })
    totalemploymentStatus.value.push({
      name:element.name,
      value:taptotal2
    })
});
console.log(totalemploymentIntents.value);



      // 默认选择“2022级”数据
      const defaultGrade = "2025级";
      const defaultIntentData =
        employmentIntents.value.find((item) => item.name === defaultGrade)
          ?.employmentIntent || employmentIntents.value[0]?.employmentIntent || [];
      const defaultStatusData =
        employmentStatus.value.find((item) => item.name === defaultGrade)
          ?.employmentStatu || employmentStatus.value[0]?.employmentStatu || [];

      value.value = defaultGrade;

      // 初始化默认图表数据
      initEmploymentIntentionChart(employmentIntentionDom.value, defaultIntentData);
      initEmploymentStatusChart(employmentStatusDom.value, defaultStatusData);
    }
  });
});


const updateChartData = (selectedGrade) => {
  const intentData = employmentIntents.value.find((item) => item.name === selectedGrade)?.employmentIntent || [];
  const statusData = employmentStatus.value.find((item) => item.name === selectedGrade)?.employmentStatu || [];


  // console.log(intentData);
  // console.log(statusData);
  if (!intentData.length && !statusData.length) {
    console.warn(`未找到 ${selectedGrade} 的数据`);
    return;
  }

  if (employmentIntentionChart) {
    employmentIntentionChart.setOption({
      series: [{ data: intentData }],
    });
  }

  if (employmentStatusChart) {
    employmentStatusChart.setOption({
      series: [{ data: statusData }],
    });
  }
};




// 响应式调整图表尺寸
const resizeCharts = () => {
  if (employmentIntentionChart) employmentIntentionChart.resize();
  if (employmentStatusChart) employmentStatusChart.resize();
};


// watch(() => props.selectGrade, (newVal, oldVal) => {
//   console.log(oldVal);
//   if (newVal) {
//     console.log('选择的年级更改了');
//     updateChartData(newVal);
//   }
// });
watch(() => props.selectedGrade, (newVal) => {
  if (newVal) {
    // console.log(newVal);
    updateChartData(newVal);
  }
});
</script>



<style lang="scss" scoped>
.outbox {
  height: 87vh;
  display: flex;
  flex-direction: column;
  position: relative;
  justify-content: space-around;
  width: 100%;

  .chart-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 20px;

    .chart-title {
      font-size: 20px;
      font-weight: bold;
      color: #00b6ff;
      margin-bottom: 10px;
    }

    .outbox-employment-intention,
    .outbox-employment-status {
      height: 35vh;
      width: 100%;
      border: 3px solid #37a2da;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      animation: borderPulse 1.5s infinite;
    }

    .outbox-employment-intention:hover,
    .outbox-employment-status:hover {
      border-color: #32c5e9;
    }
  }
}

@keyframes borderPulse {
  0% {
    border-color: #37a2da;
  }
  50% {
    border-color: #67e0e3;
  }
  100% {
    border-color: #249bdb;
  }
}
</style>